package com.yj.suncity.publish;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yj.suncity.R;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.DialogUtils.ItemCall;
import com.yj.suncity.utis.DialogUtils.ItemSelect;
import com.yj.suncity.utis.HttpUtil;
import com.yj.suncity.utis.ProgressUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.UploadUtil;
import com.yj.suncity.utis.UploadUtil.OnUploadProcessListener;

public class PublishProductActivity extends Activity implements
		OnClickListener, OnItemClickListener {
	private Uri photoUri;// 照片路径
	private final int PIC_FROM_CAMERA = 0x10086;// 拍照
	private final int PIC_FROM_LOCALPHOTO = 0x10087;// 设置图片
	private final int PIC_FROM_IMAGE = 0x10088;// 从本地选择图片
	
	private String photoName = "";
    /* 请求码 */  
    private static final int IMAGE_REQUEST_CODE = 0;  
    private static final int SELECT_PIC_KITKAT = 3;  
    private static final int CAMERA_REQUEST_CODE = 1;  
    private static final int RESULT_REQUEST_CODE = 2; 
	
	private static final int FAIL = 1;
	private static final int SUCCESS = 2;
	private static final int IO_EXCEPTION = 3;
	private static final int JSON_EXCEPTION = 4;
	private Context context;
	private String userId;
	private String releaseType;
//	private View layout, view_div;
	// private RelativeLayout mLay_rela_gallery;
	private TextView mTxt_title_name,mTxt_leixing,mTxt_peisong,mTxt_mianfei,mTxt_goumai;
	private List<NameValuePair> pairs = new ArrayList<NameValuePair>();
	private String picPath;// 拍照后保存图片的路径
	// private GalleryFlow mPublish_img_gallery;
	private ProgressUtil progressUtil;
	private ArrayList<String> uploadPaths = new ArrayList<String>();
	private EditText mEdt_good_name, mEdt_good_price, mEdt_good_num,
			mEdt_goods_real_price, mEdt_good_summary,
			mEdt_good_detail;
//	private Spinner mGoodsTypeSpinner;
	private List<String> data_list;
//	private ImageView mDeliveryImag_on, mDeliveryImag_off,mTypeImag_on, mTypeImag_off,mShopImag_on, mShopImag_off;
	private int mDelivery = 0,mType = 0,mShop = 0,mBuyType = 0;
	private Button mBtn_add_img;
	private RelativeLayout mLay_rela_img;
	private TextView mTxt_img_num;
	private ImageView mImg_all_logo;
	private DisplayImageOptions options; // 显示图片的设置
	private ImageLoader imageLoader = ImageLoader.getInstance();

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case FAIL:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, ""+(String)msg.obj);
				break;
			case SUCCESS:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, "上传成功！");
				PublishProductActivity.this.finish();
				break;
			case IO_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, "网络异常！");
				break;
			case JSON_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, "数据解析异常！");
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_publish_product);
		context = this;
		userId = getIntent().getStringExtra("userid");
		releaseType = getIntent().getStringExtra("release");
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		findView();
	}

	private void findView() {
//		layout = findViewById(R.id.lay_linear_digou);
//		view_div = findViewById(R.id.view_div);
		// mLay_rela_gallery = (RelativeLayout)
		// findViewById(R.id.lay_rela_gallery);
		// mLay_rela_gallery.setLayoutParams(new
		// LinearLayout.LayoutParams(mWidth,
		// mWidth / 3));
		// mPublish_img_gallery = (GalleryFlow)
		// findViewById(R.id.publish_img_gallery);
		// setAdapter();
		// mPublish_img_gallery.setOnItemClickListener(this);
//		mGoodsTypeSpinner = (Spinner)findViewById(R.id.goods_type_spinner);
//		mDeliveryImag_on = (ImageView)findViewById(R.id.delivery_img_on);
//		mDeliveryImag_off = (ImageView)findViewById(R.id.delivery_img_off);
//		mTypeImag_on = (ImageView)findViewById(R.id.type_img_on);
//		mTypeImag_off = (ImageView)findViewById(R.id.type_img_off);
//		mShopImag_on = (ImageView)findViewById(R.id.shop_img_on);
//		mShopImag_off = (ImageView)findViewById(R.id.shop_img_off);
		mTxt_leixing = (TextView)findViewById(R.id.goods_type_text);
		mTxt_peisong = (TextView)findViewById(R.id.peisong_type_text);
		mTxt_mianfei = (TextView)findViewById(R.id.mianfei_type_text);
		mTxt_goumai = (TextView)findViewById(R.id.goumai_type_text);

		mBtn_add_img = (Button) findViewById(R.id.btn_add_img);
		mBtn_add_img.setOnClickListener(this);
		mLay_rela_img = (RelativeLayout) findViewById(R.id.lay_rela_img);
		mTxt_img_num = (TextView) findViewById(R.id.txt_img_num);
		mImg_all_logo = (ImageView) findViewById(R.id.img_all_logo);
		mImg_all_logo.setOnClickListener(this);

		mTxt_title_name = (TextView) findViewById(R.id.txt_title_name);
//		mTxt_address = (TextView) findViewById(R.id.txt_address);
		if (releaseType.equals("1")) {
//			layout.setVisibility(View.GONE);
//			view_div.setVisibility(View.GONE);
			mTxt_title_name.setText("商家商品");
//			mTxt_address.setText("兑换地址");
		} else {
//			layout.setVisibility(View.VISIBLE);
//			view_div.setVisibility(View.VISIBLE);
			mTxt_title_name.setText("抵购商品");
//			mTxt_address.setText("抵购地址");
		}
		//数据
        data_list = new ArrayList<String>();
        data_list.add("特价");
        data_list.add("促销");
        data_list.add("精品");
        data_list.add("免费");
		ArrayAdapter<String> arr_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list);
//		mGoodsTypeSpinner.setAdapter(arr_adapter);
		mEdt_good_name = (EditText) findViewById(R.id.edt_product_name);
		mEdt_good_price = (EditText) findViewById(R.id.edt_product_price);
		mEdt_good_num = (EditText) findViewById(R.id.edt_product_num);
		mEdt_goods_real_price = (EditText)findViewById(R.id.edt_product_real_price);
		
		mEdt_good_summary = (EditText)findViewById(R.id.edt_product_summary);
		mEdt_good_detail = (EditText) findViewById(R.id.edt_product_detail);
		
//		mGoodsTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
//
//			@Override
//			public void onItemSelected(AdapterView<?> parent, View view,
//					int position, long id) {
//				// TODO Auto-generated method stub
//				mBuyType = position + 1;
//				
//			}
//
//			@Override
//			public void onNothingSelected(AdapterView<?> parent) {
//				// TODO Auto-generated method stub
//				
//			}
//		});
	}

	/**
	 * 重置图片布局
	 */
	private void setAdapter() {
		// mPublish_img_gallery.setAdapter(new PublishGalleryAdapter(context,
		// uploadPaths));
		// if (uploadPaths.size() > 0) {
		// mPublish_img_gallery.setSelection(1);
		// }
		if (uploadPaths.size() == 9) {
			mBtn_add_img.setVisibility(View.GONE);
			mLay_rela_img.setVisibility(View.VISIBLE);
			mTxt_img_num.setText(String.valueOf(uploadPaths.size()));
			imageLoader.displayImage("file://" + uploadPaths.get(0),
					mImg_all_logo, options);
		} else if (uploadPaths.size() < 9 && uploadPaths.size() > 0) {
			mBtn_add_img.setVisibility(View.VISIBLE);
			mLay_rela_img.setVisibility(View.VISIBLE);
			mTxt_img_num.setText(String.valueOf(uploadPaths.size()));
			imageLoader.displayImage("file://" + uploadPaths.get(0),
					mImg_all_logo, options);
		} else {
			mBtn_add_img.setVisibility(View.VISIBLE);
			mLay_rela_img.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
		case R.id.btn_add_img:// 添加图片按钮
			popView();
			break;
		case R.id.img_all_logo:// 点击图片查看
			Bundle bundle = new Bundle();
			bundle.putStringArrayList("paths", uploadPaths);
			bundle.putInt("posi", 0);
			Intent intent = new Intent(context, SelectPicShowActivity.class);
			intent.putExtras(bundle);
			startActivityForResult(intent, 103);
			break;
		case R.id.btn_ok:

			String goodName = mEdt_good_name.getText().toString().trim();
			String goodPrice = mEdt_good_price.getText().toString().trim();
			String goodNum = mEdt_good_num.getText().toString().trim();
			String goodRealPrice = mEdt_goods_real_price.getText().toString()
					.trim();
			String goodSummary = mEdt_good_summary.getText().toString().trim();
			String goodDetail = mEdt_good_detail.getText().toString().trim();
			if (uploadPaths.size() <= 0) {
				ToastUtil.ShowToast(context, "请添加商品图片！");
				return;
			}
			if (goodName.equals("")) {
				ToastUtil.ShowToast(context, "请输入商品名称！");
				return;
			}
			if (goodPrice.equals("")) {
				ToastUtil.ShowToast(context, "请输入店内价格！");
				return;
			}
			if (goodNum.equals("")) {
				ToastUtil.ShowToast(context, "请输入商品数量！");
				return;
			}
				if (goodRealPrice.equals("")) {
					ToastUtil.ShowToast(context, "请输入商品现价！");
					return;
				}
			if (goodSummary.equals("")) {
				ToastUtil.ShowToast(context, "请输入商品简介！");
				return;
			}
			if (goodDetail.equals("")) {
				ToastUtil.ShowToast(context, "请输入商品详情！");
				return;
			}
			if(mDelivery == 0){
				ToastUtil.ShowToast(context, "请选择配送方式！");
				return;
			}
			if(mType == 0){
				ToastUtil.ShowToast(context, "请选择配送资费！");
				return;
			}
			if(mShop == 0){
				ToastUtil.ShowToast(context, "请选择购买方式！");
				return;
			}
			if(mBuyType == 0){
				ToastUtil.ShowToast(context, "请选择商品类型！");
				return;
			}
			uploadImg(goodName, goodPrice, goodNum, goodRealPrice, goodSummary,
					goodDetail);

			break;
		case R.id.leixing_layout:
			final String[] items = new String[] { "特价", "促销","精品","免费" };
			new AlertDialog.Builder(this).setTitle("选择商品类型").setItems(items, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					mTxt_leixing.setText(items[which]);
					mBuyType = which + 1;
					
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).show();
			break;
		case R.id.is_delivery:
			final String[] delitems = new String[] { "支持本地配送", "不支持本地配送" };
			new AlertDialog.Builder(this).setTitle("选择配送方式").setItems(delitems, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					mTxt_peisong.setText(delitems[which]);
					mDelivery = which + 1;
					
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).show();
			// 本地配送
//			if (mDelivery == 2) {
//				mDelivery = 1;
//				mDeliveryImag_off.setVisibility(View.INVISIBLE);
//				mDeliveryImag_on.setVisibility(View.VISIBLE);
//			} else {
//				mDelivery = 2;
//				mDeliveryImag_off.setVisibility(View.VISIBLE);
//				mDeliveryImag_on.setVisibility(View.INVISIBLE);
//			}
			break;
		case R.id.is_type:
			// 免费配送
			final String[] mianfeiitems = new String[] { "免费配送", "自费配送" };
			new AlertDialog.Builder(this).setTitle("选择配送资费").setItems(mianfeiitems, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					mTxt_mianfei.setText(mianfeiitems[which]);
					mType = which + 1;
					
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).show();
//			final ArrayList<String> mianfei_list = new ArrayList<String>();
//			mianfei_list.add("免费配送");
//			mianfei_list.add("自费配送");
//			new DialogUtils().listDialog(getApplicationContext(), mianfei_list, new ItemSelect() {
//				
//				@Override
//				public void itemSelect(int pos) {
//					// TODO Auto-generated method stub
//					mType = pos+1;
//					mTxt_mianfei.setText(mianfei_list.get(pos));
//				}
//			});
//			if (mType == 2) {
//				mType = 1;
//				mTypeImag_off.setVisibility(View.INVISIBLE);
//				mTypeImag_on.setVisibility(View.VISIBLE);
//			} else {
//				mType = 2;
//				mTypeImag_off.setVisibility(View.VISIBLE);
//				mTypeImag_on.setVisibility(View.INVISIBLE);
//			}
			break;
		case R.id.is_shop:
			final String[] goumaiitems = new String[] { "支持店内购买", "不支持店内购买" };
			new AlertDialog.Builder(this).setTitle("选择购买方式").setItems(goumaiitems, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					mTxt_goumai.setText(goumaiitems[which]);
					mShop = which + 1;
					
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).show();
//			final ArrayList<String> goumai_list = new ArrayList<String>();
//			goumai_list.add("支持店内购买");
//			goumai_list.add("不支持店内购买");
//			new DialogUtils().listDialog(getApplicationContext(), goumai_list, new ItemSelect() {
//				
//				@Override
//				public void itemSelect(int pos) {
//					// TODO Auto-generated method stub
//					mShop = pos+1;
//					mTxt_goumai.setText(goumai_list.get(pos));
//				}
//			});
			// 店内购买
//			if (mShop == 2) {
//				mShop = 1;
//				mShopImag_off.setVisibility(View.INVISIBLE);
//				mShopImag_on.setVisibility(View.VISIBLE);
//			} else {
//				mShop = 2;
//				mShopImag_off.setVisibility(View.VISIBLE);
//				mShopImag_on.setVisibility(View.INVISIBLE);
//			}
			break;
		}
	}

	private StringBuffer stringBuffer = new StringBuffer();

	private void uploadImg(final String goodName, final String goodPrice,
			final String goodNum, final String realPrice,
			final String goodSummary, final String goodDetail) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("action", "uploads");
		UploadUtil uploadUtil = new UploadUtil();
		progressUtil = new ProgressUtil();
		progressUtil.ShowProgress(context, true, false, "正在上传......");
		uploadUtil.uploadFile(context, uploadPaths, "txtimg", URLCon.图片上传,
				param, new OnUploadProcessListener() {
					@Override
					public void UploadResule(String result) {
						Log.d("", "result===" + result);
						try {
							JSONObject jsonObject = new JSONObject(result);
							if (jsonObject.optString("success").equals("1")) {
								JSONArray array = jsonObject
										.optJSONArray("data");
								stringBuffer.delete(0, stringBuffer.length());
								for (int i = 0; i < array.length(); i++) {
									String url = array.optJSONObject(i)
											.optString("url");
									stringBuffer.append(url + ",");
								}
								stringBuffer.deleteCharAt(stringBuffer.length() - 1);

								publishProduct(goodName, goodPrice, goodNum,
										 goodSummary, goodDetail,realPrice);

							} else {
								Message message = new Message();
								message.what = FAIL;
								message.obj = jsonObject.optString("msg");
								handler.sendMessage(message);
							}
						} catch (JSONException e) {
							Message message = new Message();
							message.what = JSON_EXCEPTION;
							handler.sendMessage(message);
							e.printStackTrace();
						}
					}
				});
	}

	private void publishProduct(String goodName, String goodPrice,
			String goodNum, String goodSummary, 
			String goodDetail, String realPrice) {
		pairs.clear();
		final String path = URLCon.发布商品;
		pairs.add(new BasicNameValuePair("action", "publishgoods"));
		pairs.add(new BasicNameValuePair("userid", userId));
//		pairs.add(new BasicNameValuePair("release_type", releaseType));
		pairs.add(new BasicNameValuePair("goods_title", goodName));
		pairs.add(new BasicNameValuePair("buy_type", mBuyType+""));
		pairs.add(new BasicNameValuePair("is_shoppurchase", mShop+""));
		pairs.add(new BasicNameValuePair("good_num", goodNum));
		pairs.add(new BasicNameValuePair("is_delivery", mDelivery+""));
		pairs.add(new BasicNameValuePair("goods_price", goodPrice));
		pairs.add(new BasicNameValuePair("delivery_type", mType+""));
		pairs.add(new BasicNameValuePair("goods_summary", goodSummary));
		pairs.add(new BasicNameValuePair("txtimg", stringBuffer.toString()));
		pairs.add(new BasicNameValuePair("goods_content", goodDetail));
		pairs.add(new BasicNameValuePair("real_price", realPrice));

		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String json = HttpUtil.HttpClientdoPost(path, pairs);
					JSONObject jsonObject = new JSONObject(json);
					Message message = new Message();
					if (jsonObject.optString("success").equals("1")) {
						message.what = SUCCESS;
					} else {
						message.what = FAIL;
						message.obj = jsonObject.optString("msg");
					}
					handler.sendMessage(message);

				} catch (IOException e) {
					Message message = new Message();
					message.what = IO_EXCEPTION;
					handler.sendMessage(message);
					e.printStackTrace();
				} catch (JSONException e) {
					Message message = new Message();
					message.what = JSON_EXCEPTION;
					handler.sendMessage(message);
					e.printStackTrace();
				}
			}
		});
		thread.start();
		thread = null;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// if (position == 0) {
		// popView();
		// } else {
		// Bundle bundle = new Bundle();
		// bundle.putStringArrayList("paths", uploadPaths);
		// bundle.putInt("posi", position - 1);
		// Intent intent = new Intent(context, SelectPicShowActivity.class);
		// intent.putExtras(bundle);
		// startActivityForResult(intent, 103);
		// }
	}

	private void popView() {
		DialogUtils dialogUtils = DialogUtils.getInstance();
		dialogUtils.SelectPicDialog(context, new ItemCall() {
			@Override
			public void onIndexCall(int index) {
				if (index == 0) {// 拍照
					 Intent intentFromCapture = new Intent(  
                             MediaStore.ACTION_IMAGE_CAPTURE);  
                     // 判断存储卡是否可以用，可用进行存储  
                     if (hasSdcard()) {  
                    	 photoName = getPhotoFileName();
                         intentFromCapture.putExtra(  
                                 MediaStore.EXTRA_OUTPUT,  
                                 Uri.fromFile(new File(Environment  
                                         .getExternalStorageDirectory(),  
                                         photoName)));  
                     }else {  
                         ToastUtil.ShowToast(context,"未找到存储卡，无法存储照片！");  
                     }  
                     startActivityForResult(intentFromCapture,  
                             CAMERA_REQUEST_CODE);
//					doHandlerPhoto(PIC_FROM_CAMERA);
				} else if (index == 1) {// 相册
					photoName = getPhotoFileName();
					Intent intent=new Intent(Intent.ACTION_GET_CONTENT);  
                    intent.addCategory(Intent.CATEGORY_OPENABLE);  
                    intent.setType("image/*");  
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {  
                        startActivityForResult(intent,SELECT_PIC_KITKAT);  
                    } else {  
                        startActivityForResult(intent,IMAGE_REQUEST_CODE);  
                    }  
				}
			}
		});
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// upImgPath.clear();
		// 拍照后返回的数据
		if (resultCode != RESULT_CANCELED) {  
            switch (requestCode) {  
            case IMAGE_REQUEST_CODE:  
                startPhotoZoom(data.getData());  
                break;  
            case SELECT_PIC_KITKAT:  
                startPhotoZoom(data.getData());  
                break;  
            case CAMERA_REQUEST_CODE:  
                if (hasSdcard()) {  
                    File tempFile = new File(Environment.getExternalStorageDirectory(),photoName);  
                    startPhotoZoom(Uri.fromFile(tempFile));  
                } else {  
                    ToastUtil.ShowToast(context,"未找到存储卡，无法存储照片！");  
                }  

                break;  
            case RESULT_REQUEST_CODE:  
                if (data != null) {  
                	setImageToView(data);
                	
                	File file = new File(Environment.getExternalStorageDirectory(),photoName);  
                	picPath=file.getAbsolutePath();
        			if (BitmapFactory.decodeFile(picPath) == null) {
        				break;
        			}
        			uploadPaths.add(picPath);
        			if (uploadPaths.size() > 9) {
        				uploadPaths.remove(picPath);
        				ToastUtil.ShowToast(context, "您最多可以选择9张图片！");
        				return;
        			}
        			
        			 setAdapter();
                }  
                break;  
            }  
        } 
//		switch (requestCode) {
//		case PIC_FROM_IMAGE:// 从本地选择照片
//			if (photoUri == null) {
//				break;
//			}
//			picPath = photoUri.toString().replace("file://", "");
//			if (BitmapFactory.decodeFile(picPath) == null) {
//				break;
//			}
//			uploadPaths.add(picPath);
//			if (uploadPaths.size() > 9) {
//				uploadPaths.remove(picPath);
//				ToastUtil.ShowToast(context, "您最多可以选择9张图片！");
//				return;
//			}
//			// setAdapter();
//			break;
//		case PIC_FROM_CAMERA: // 拍照选择相片
//			try {
//				cropImageUriByTakePhoto();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			break;
//		}
//		setAdapter();

		// 查看选择的图片后并且将图片全部删除后返回的数据
		if (requestCode == 103 && resultCode == 104) {
			uploadPaths.clear();
			setAdapter();
		}

		// 查看选择的图片后返回的数据
		if (requestCode == 103 && resultCode == 103) {
			List<String> paths = data.getStringArrayListExtra("picPaths");
			if (paths != null && paths.size() > 0) {
				// imaLayout.removeAllViews();
				uploadPaths.clear();
				uploadPaths.addAll(paths);
				// 利用HashSet过滤掉一样的路径
				HashSet<String> set = new HashSet<String>(uploadPaths);
				uploadPaths.clear();
				uploadPaths.addAll(set);

				setAdapter();
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}
	/**  
     * 保存裁剪之后的图片数据  
     *   
     * @param picdata  
     */  
    private void setImageToView(Intent data) {  
        Bundle extras = data.getExtras();  
        if (extras != null) {  
            Bitmap photo = extras.getParcelable("data");   
            saveBitmap(photo);  
        }  
    }  

    public void saveBitmap(Bitmap mBitmap) {  
    	if("".equals(photoName) || photoName == null){
    		photoName = getPhotoFileName();
    	}
        File f = new File(Environment.getExternalStorageDirectory(),photoName);  
        try {  
            f.createNewFile();  
            FileOutputStream fOut = null;  
            fOut = new FileOutputStream(f);  
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);  
            fOut.flush();  
            fOut.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {

		if (uri == null) {  
            Log.i("tag", "The uri is not exist.");  
            return;  
        }  
          
        Intent intent = new Intent("com.android.camera.action.CROP");  
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {  
            String url=getPath(context,uri);  
            intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");  
        }else{  
            intent.setDataAndType(uri, "image/*");  
        }  
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 240);
		intent.putExtra("outputY", 240);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, RESULT_REQUEST_CODE);
	}
	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	private void getImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
//			photo = Utils.toRoundCorner(photo,20);
			saveBitmap(photo);
			
//			uploadPaths.remove(0);
			uploadPaths.add(picPath);
			setAdapter();
		}
	}
//	private void saveBitmap(Bitmap bitmap){
//		String picName = getPhotoFileName();// 拍照后保存的图片名
//
//		picPath = Environment.getExternalStorageDirectory()
//				+ "/DCIM/Camera/" + picName;// 保存图片的路径
//		File dir = new File(Environment.getExternalStorageDirectory()+ "/DCIM/Camera/");
//		if (!dir.exists()) {
//			dir.mkdirs();
//		}
//		File bitmapFile = new File(picPath);
//
//		if (!bitmapFile.exists()) {
//			try {
//				bitmapFile.createNewFile();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
//		FileOutputStream fos;
//		try {
//			fos = new FileOutputStream(bitmapFile);
//			bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
//			fos.close();
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}
	/**
	 * 调用相机拍照
	 */
	private void startPaizhao() {
		// 执行拍照前，应该先判断SD卡是否存在
		String SDState = Environment.getExternalStorageState();
		if (SDState.equals(Environment.MEDIA_MOUNTED)) {
			Intent intent = new Intent(
					android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			/**
			 * 需要说明一下，以下操作使用照相机拍照，拍照后的图片会存放在相册中的 这里使用的这种方式有一个好处就是获取的图片是拍照后的原图
			 * 如果不实用ContentValues存放照片路径的话，拍照后获取的图片为缩略图不清晰
			 */
			// --------------------------------------------------------//
			String picName = getPhotoFileName();// 拍照后保存的图片名

			picPath = Environment.getExternalStorageDirectory()
					+ "/DCIM/Camera/" + picName;// 保存图片的路径
			File mPhotoFile = new File(picPath);// File
			if (!mPhotoFile.exists()) {
				try {
					mPhotoFile.createNewFile();
				} catch (IOException e) {
					Log.d("", e.getMessage());
					e.printStackTrace();
				}
			}
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));

			startActivityForResult(intent, 110);
		} else {
			ToastUtil.ShowToast(context, "内存卡不存在！");
		}
	}

	/**
	 * 调用相册选取照片
	 */
	private void startXiangce() {
		if (hasSdcard()) {
			Intent intentFromGallery = new Intent();
			intentFromGallery.setType("image/*"); // 设置文件类型
			intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(intentFromGallery, 104);
		} else {
			Toast.makeText(getApplicationContext(), "请插入SD卡！", Toast.LENGTH_SHORT).show();
		}
//		Intent intent = new Intent(context, PicSelectActivity.class);
//		intent.putExtra("picPathSize", uploadPaths.size());
//		startActivityForResult(intent, 103);
	}
	public static boolean hasSdcard() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 用时间戳生成照片名称
	 * 
	 * @return
	 */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'yyyyMMddHHmmss");
		return dateFormat.format(date) + ".jpg";
	}
	 //以下是关键，原本uri返回的是file:///...来着的，android4.4返回的是content:///...  
    @SuppressLint("NewApi")
	public static String getPath(final Context context, final Uri uri) {  

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;  

        // DocumentProvider  
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {  
            // ExternalStorageProvider  
            if (isExternalStorageDocument(uri)) {  
                final String docId = DocumentsContract.getDocumentId(uri);  
                final String[] split = docId.split(":");  
                final String type = split[0];  

                if ("primary".equalsIgnoreCase(type)) {  
                    return Environment.getExternalStorageDirectory() + "/" + split[1];  
                }  

            }  
            // DownloadsProvider  
            else if (isDownloadsDocument(uri)) {  
                final String id = DocumentsContract.getDocumentId(uri);  
                final Uri contentUri = ContentUris.withAppendedId(  
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));  

                return getDataColumn(context, contentUri, null, null);  
            }  
            // MediaProvider  
            else if (isMediaDocument(uri)) {  
                final String docId = DocumentsContract.getDocumentId(uri);  
                final String[] split = docId.split(":");  
                final String type = split[0];  

                Uri contentUri = null;  
                if ("image".equals(type)) {  
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;  
                } else if ("video".equals(type)) {  
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;  
                } else if ("audio".equals(type)) {  
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;  
                }  

                final String selection = "_id=?";  
                final String[] selectionArgs = new String[] {  
                        split[1]  
                };  

                return getDataColumn(context, contentUri, selection, selectionArgs);  
            }  
        }  
        // MediaStore (and general)  
        else if ("content".equalsIgnoreCase(uri.getScheme())) {  
            // Return the remote address  
            if (isGooglePhotosUri(uri))  
                return uri.getLastPathSegment();  

            return getDataColumn(context, uri, null, null);  
        }  
        // File  
        else if ("file".equalsIgnoreCase(uri.getScheme())) {  
            return uri.getPath();  
        }  

        return null;  
    }  

    /** 
     * Get the value of the data column for this Uri. This is useful for 
     * MediaStore Uris, and other file-based ContentProviders. 
     * 
     * @param context The context. 
     * @param uri The Uri to query. 
     * @param selection (Optional) Filter used in the query. 
     * @param selectionArgs (Optional) Selection arguments used in the query. 
     * @return The value of the _data column, which is typically a file path. 
     */  
    public static String getDataColumn(Context context, Uri uri, String selection,  
            String[] selectionArgs) {  

        Cursor cursor = null;  
        final String column = "_data";  
        final String[] projection = {  
                column  
        };  

        try {  
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,  
                    null);  
            if (cursor != null && cursor.moveToFirst()) {  
                final int index = cursor.getColumnIndexOrThrow(column);  
                return cursor.getString(index);  
            }  
        } finally {  
            if (cursor != null)  
                cursor.close();  
        }  
        return null;  
    }  


    /** 
     * @param uri The Uri to check. 
     * @return Whether the Uri authority is ExternalStorageProvider. 
     */  
    public static boolean isExternalStorageDocument(Uri uri) {  
        return "com.android.externalstorage.documents".equals(uri.getAuthority());  
    }  

    /** 
     * @param uri The Uri to check. 
     * @return Whether the Uri authority is DownloadsProvider. 
     */  
    public static boolean isDownloadsDocument(Uri uri) {  
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());  
    }  

    /** 
     * @param uri The Uri to check. 
     * @return Whether the Uri authority is MediaProvider. 
     */  
    public static boolean isMediaDocument(Uri uri) {  
        return "com.android.providers.media.documents".equals(uri.getAuthority());  
    }  

    /** 
     * @param uri The Uri to check. 
     * @return Whether the Uri authority is Google Photos. 
     */  
    public static boolean isGooglePhotosUri(Uri uri) {  
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());  
    } 
}
